package com.yyt.yytojbackendjudgeservice.judge;

import cn.hutool.json.JSONUtil;

import com.yyt.yytojbackendcommon.common.ErrorCode;
import com.yyt.yytojbackendcommon.exception.BusinessException;
import com.yyt.yytojbackendjudgeservice.judge.codesandbox.CodeSandbox;
import com.yyt.yytojbackendjudgeservice.judge.codesandbox.CodeSandboxFactory;
import com.yyt.yytojbackendjudgeservice.judge.codesandbox.CodeSandboxProxy;
import com.yyt.yytojbackendjudgeservice.judge.strategy.JudgeContext;
import com.yyt.yytojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.yyt.yytojbackendmodel.model.codesandbox.ExecuteCodeResponce;
import com.yyt.yytojbackendmodel.model.codesandbox.JudgeInfo;
import com.yyt.yytojbackendmodel.model.dto.question.JudgeCase;
import com.yyt.yytojbackendmodel.model.entity.Question;
import com.yyt.yytojbackendmodel.model.entity.QuestionSubmit;
import com.yyt.yytojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.yyt.yytojbackendserviceclient.service.QuestionFeignClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService{
    @Resource
    private QuestionFeignClient questionFeignClient;


    @Value("${codesandbox.type:example}")
    private String type;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //（1）传入题目提交的id，获取到对应的题目、提交信息（包含代码、编程语言等）
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if(questionSubmit==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeignClient.getQuestionById(questionId);
        if(question==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        //判断是否为等待状态
        if(questionSubmit.getStatus()!= QuestionSubmitStatusEnum.WAITING.getValue()){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"正在判题中");
        }
        //如果为等待状态，更改判题状态为判题中
        QuestionSubmit questionSubmitUpdate=new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNING.getValue());
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"判题状态修改失败");
        }
        String code = questionSubmit.getCode();
        String language = questionSubmit.getCodeLanguage();
        //获得输入用例
        String judgeCase = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCase, JudgeCase.class);
        List<String> inputList=judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());

        //（2）调用沙箱获取到执行结果
        CodeSandbox codeSandbox= CodeSandboxFactory.newInstance(type);
        codeSandbox= new CodeSandboxProxy(codeSandbox);
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .inputList(inputList)
                .codeLanguage(language)
                .code(code)
                .build();
        ExecuteCodeResponce executeCodeResponce = codeSandbox.executeCode(executeCodeRequest);
        List<String> outputList = executeCodeResponce.getOutputList();

        //（3）根据沙箱的执行结果，设置判题状态——使用策略模式优化
        JudgeInfo judgeInfo=executeCodeResponce.getJudgeInfo();
        JudgeContext judgeContext=JudgeContext.builder()
                .judgeInfo(judgeInfo)
                .inputList(inputList)
                .outputList(outputList)
                .question(question)
                .build();
        JudgeManager judgeManager = new JudgeManager();
        JudgeInfo judgeInfoResponce=judgeManager.doJudge(judgeContext, language);
        //根据返回结果更改数据库中判题结果
        questionSubmitUpdate=new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCESS.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfoResponce));
        update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        return questionSubmitResult;
    }
}
